﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Collections.Specialized;
using System.Configuration;

namespace WebApi
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_BeginRequest(Object source, EventArgs e)
        {
            NameValueCollection headers = HttpContext.Current.Request.Headers;

            var keys = (from h in headers.AllKeys
                    select h).ToList();

            var action = (from k in keys
                          where k.Equals("action")
                          select k).SingleOrDefault();

            var paths = HttpContext.Current.Request.Path.Split(new char[] {'/'});
            var actionPath = paths[paths.Length - 1];
            var controllerPath = paths[paths.Length - 2];

            if (controllerPath == "PopUpJoe" || controllerPath == "Report" || controllerPath == "Cache")
            {

            }
            else if (action == null || actionPath != Crypto.Cryptor.Decrypt(headers[action], ConfigurationManager.AppSettings.Get("EncryptPassword")))
            {
                HttpContext.Current.Response.StatusCode = 403;
                (source as HttpApplication).CompleteRequest();
            }
        }
    }
}